﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using NHibernate;
using Eshouse.Entity;

namespace Eshouse.Bll
{
   /// <summary>
   /// 类型操作逻辑，1、如果是ajax类型名称检测，或者是ajax返回单个值等对性能要求高，而且sql语句可以实现多数据库兼容时(如：查询一个值)，就采用ADO.NET方式，其他插入、修改采用NHIBERNATE方式
   /// </summary>
    public class catagoryAccess:IDisposable
    {
        protected ISession Session { get; set; }
        public catagoryAccess()
        {
             NHibernateHelper Nhelper = new NHibernateHelper();
            Session = Nhelper.GetSession();
        }
        /// <summary>
        /// 添加一个类型
        /// </summary>
        /// <param name="catagory"></param>
        /// <returns></returns>
        public bool InsertCatagroy(DicCode catagory)
        {
            CRC32Primarykey crc=new CRC32Primarykey();
            bool secces = true;
            DateTime now=DateTime.Now;
            int primaryKey = crc.createIntID("dict" + now.ToString("yyyyMMddhhmmss") + now.Millisecond.ToString());
            catagory.Id = primaryKey;
            try
            {
                Session.Save(catagory);
                Session.Flush();
            }
            catch (Exception ex)
            {
                logRecord.RecordErr("添加类型", ex);
                secces = false;
            }
            //DatabaseHelper db = new DatabaseHelper();
            //string sql = "insert into DicCode(dictID,DictName) values (@id,@name)";
            //db.AddParameter("@id", primaryKey);
            //db.AddParameter("@name", catagory.DictName);
            //if (db.ExecuteNonQuery(sql) <= 0)
            //    secces = false;
            return secces;
        }
        /// <summary>
        /// 检测用户名是否存在,ADO.net方式,实时检测要求性能高一点，不采用NHibernate
        /// </summary>
        /// <param name="catagoryName">类型名称</param>
        /// <returns></returns>
        public static bool VerifyCatagoryName(string catagoryName)
        {
            bool isexist = false;
            string strSql = "select dictID from DicCode where dictName='{0}'";
            DatabaseHelper dbhelper = new DatabaseHelper();
            object o= dbhelper.ExecuteScalar(string.Format(strSql,catagoryName.Trim()));
            if (o != null)
                isexist = true;
            return isexist;
        }
        /// <summary>
        /// 获取所有类型信息
        /// </summary>
        /// <returns></returns>
        public IList<DicCode> GetCatagoryList()
        {
            IList<DicCode> list;
            try
            {
                list = Session.CreateQuery("from DicCode").List<DicCode>();
            }catch(Exception ex)
            {
               logRecord.RecordErr("获取所有类型信息失败", ex);
                list= null;
            }
            return list;
        }
        /// <summary>
        /// 分页获取
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public DataTable GetList(int pageIdx, int size)
        {
            DataTable dt = new DataTable();
            DataColumn col = new DataColumn("id");
            DataColumn col2 = new DataColumn("catagrory");   
            dt.Columns.Add(col);
            dt.Columns.Add(col2);
            pageIdx = (pageIdx - 1) * size;
            IList<DicCode> list;
            try
            {
                list = Session.CreateCriteria(typeof(DicCode)).SetFirstResult(pageIdx).SetMaxResults(size).List<DicCode>();
            }
            catch (Exception ex)
            {
                logRecord.RecordErr("更新字典项", ex);
                list = null;
            }
            if (list != null)
            { 
            DicCode dic;
              for(int i=0;i<list.Count;i++)
              {
                  dic=list[i];
                  DataRow row = dt.NewRow();
                  row[0] = dic.Id;
                  row[1] = dic.DictName;
                  dt.Rows.Add(row);
              }
            
            }

            return dt;
        }
        private int GetItemCount()
        {
            int count = 0;
            string strSql = "select count(dictID) from DicCode";
            DatabaseHelper dbhelp = new DatabaseHelper();
            object o = dbhelp.ExecuteScalar(strSql);
            if(o!=null){
                count = Convert.ToInt32(o);
            }
            return count;
        }
        public int Delete(DicCode dic)
        {
            int res = 1;
            try
            {
                Session.Delete(dic);
                Session.Flush();
            }catch(Exception ex)
            {
                logRecord.RecordErr("删除类型信息失败", ex);
                res=0;
            }
            return res;
        }
        public string GetListOnJson(int pageIdx, int size)
        {
           
            DataTable dt = GetList(pageIdx, size);
            int rowCount = GetItemCount();           
            return publicComm.GetJsonString(dt,rowCount);
        }
        /// <summary>
        /// 服务器端 对类型名称的验证
        /// </summary>
        /// <param name="catagoryName">类型名称</param>
        /// <param name="verifyResult">验证结果信息</param>
        /// <returns>是否通过验证</returns>
        public static bool VerifyCatagoryNameOnServer(string catagoryName,ref StringBuilder verifyResult)
        {
            bool verify = true;
            if (catagoryName=="")
            {
                verify = false;
                verifyResult.Append("类型名称不能为空！");
            }
            if (catagoryName.Length<2)
            {
                verify = false;
                verifyResult.Append("类型名称长度不能小于2！");
            }
            if (catagoryAccess.VerifyCatagoryName(catagoryName))
            {
                verify = false;
                verifyResult.Append("该类型名称已经存在！");
            }
            return verify;
        }

        #region IDisposable 成员
        /// <summary>
        /// 用于及时释放资源
        /// </summary>
        public void Dispose()
        {
            //if (Session.IsOpen)
            //Session.Close();
        }

        #endregion
    }
}
